﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using Database.Classes;


public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void BuySu(int pId, int quantity)
    {
        int oldSuPrice = int.Parse(GetConfigurationForOption("SupplyUnitsPrice"));
        int newPrice = oldSuPrice + quantity * 3;
        int buyPrice = oldSuPrice / 3 + 2 * newPrice / 3;
        int cash = UserDefinedFunctions.GetPlayerFloat(pId, "Cash").ToSqlInt32().Value;
        if (cash >= quantity * buyPrice)
        {
            using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("Update players SET SupplyUnits = SupplyUnits + @q, Cash = Cash - @p Where PlayerId = @pId", conn))
                {
                    //buy su
                    cmd.Parameters.Add("@q", SqlDbType.Int).Value = quantity;
                    cmd.Parameters.Add("@p", SqlDbType.Int).Value = quantity * buyPrice;
                    cmd.Parameters.Add("@pId", SqlDbType.Int).Value = pId;
                    cmd.ExecuteNonQuery();
                    //update price
                    cmd.CommandText = "Update Configuration SET SupplyUnitsPrice = @t";
                    cmd.Parameters.Add("@t", SqlDbType.Int).Value = newPrice;
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void SellSu(int pId, int quantity)
    {
        int oldSuPrice = int.Parse(GetConfigurationForOption("SupplyUnitsPrice"));
        int newPrice = oldSuPrice - quantity * 3;
        int sellPrice = oldSuPrice / 3 + 2 * newPrice / 3;
        int su = UserDefinedFunctions.GetPlayerInt(pId, "SupplyUnits").Value;
        if (quantity <= su)
        {
            using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("Update players SET SupplyUnits = SupplyUnits - @q, Cash = Cash + @p Where PlayerId = @pId", conn))
                {
                    //buy su
                    cmd.Parameters.Add("@q", SqlDbType.Int).Value = quantity;
                    cmd.Parameters.Add("@p", SqlDbType.Int).Value = quantity * sellPrice;
                    cmd.Parameters.Add("@pId", SqlDbType.Int).Value = pId;
                    cmd.ExecuteNonQuery();
                    //update price
                    cmd.CommandText = "Update Configuration SET SupplyUnitsPrice = @t";
                    cmd.Parameters.Add("@t", SqlDbType.Int).Value = newPrice;
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
};
